package cn.xianyang._05sync;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 消费者对象
 */
public class Consumer {
    public static void main(String[] args) throws Exception {

        //1.创建消费者，以推送的方式
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("hello_group_consumer");
        //2.连接mq
        consumer.setNamesrvAddr("127.0.0.1:9876");
        //3.配置监听topic{主题}和tag{消息体}
        consumer.subscribe("hello_topic_Test","hello_tags_Test");
        //4.编写处理消费消息的监听器
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt msg : msgs) {
                    try {
                        String result = new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET);
                        System.out.println(result);
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });
        //5.启动消费者
        consumer.start();
    }
}
